package com.game.ThauanLopes;

import java.util.HashSet;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;

public class mainMenu extends View implements Runnable
{
	public static boolean run;
	public final int INTERVAL = 10;
	
	private Context mainContext;
	public HashSet<GameObject> go = new HashSet<GameObject>();
	private Bitmap[] bitmap = new Bitmap[3];
	
	public mainMenu(Context context) 
	{
		super(context);
		
		run = true;
		
		mainContext = context;
		this.setBackgroundColor(Color.BLACK);
		
		bitmap[0] = BitmapFactory.decodeResource(context.getResources(), R.drawable.iniciar);
		bitmap[1] = BitmapFactory.decodeResource(context.getResources(), R.drawable.sair);
		bitmap[2] = BitmapFactory.decodeResource(context.getResources(), R.drawable.background_game);	

		Thread thread = new Thread(this);
		thread.start();
	}
	
	protected void onSizeChanged(int w, int h, int oldw, int oldh)
	{
		Background background = new Background(bitmap[2],new Rect(0,0,w,h),go);	
		ImageButton buttonPlay = new ImageButton(bitmap[0],90,400,"PLAY");
		ImageButton buttonQuit = new ImageButton(bitmap[1],90,500,"QUIT");
		
		go.add(background);
		go.add(buttonPlay);
		go.add(buttonQuit);
	}
	
	public void draw(Canvas canvas)
	{
		super.draw(canvas);
		
		if(!go.isEmpty())
		{
			for(GameObject button : go)
			{
				button.Draw(canvas);
			}
		}
	}
	
	public boolean onTouchEvent(MotionEvent event) 
	{
		switch (event.getAction()) 
		{
			case MotionEvent.ACTION_DOWN:
			
				int x = (int) event.getX(0);
				int y = (int) event.getY(0);
				
				Rect fingersPos = new Rect(x - 20,y - 20,x + 20, y + 20);
				
				if(!go.isEmpty())
				{
					for(GameObject pl : go)
					{
						if(pl.collision(fingersPos))
						{
							if(pl.tag == "PLAY")
							{
								Game game = new Game(mainContext);
								Activity act = (Activity) mainContext;
								act.setContentView(game);
							}
							if(pl.tag == "QUIT")
							{
								Activity act = (Activity) mainContext;
								killYourself(act);
							}
						}
					}
				}
				
				
				return true;

		}
		
		return super.onTouchEvent(event);
	}
	@Override
	public void run() {
		while(run)
		{
			try
			{
				Thread.sleep(INTERVAL);
			}
			catch(InterruptedException e)
			{
				Log.e("MYTAG","ERROR");
			}
			
			postInvalidate();
		}
		
	}

	public static void killYourself(Activity act)
	{
		run = false;
		act.finish();
	}
}

